03. SQLAlchemy Object Lifecycle — Part 1
SQLAlchemy Object Lifecycle - Part 1 Heading
SQLAlchemy Object Lifecycle — Part 1
Recall
We can insert new records into the database using SQLAlchemy by running
person = Person(name='Amy')
db.session.add(person)
db.session.commit()
which will build a transaction for inserting in a
person
instance in our model/table, and persist it to the database upon calling
commit()
.
ND004 C01 L04 03 SQLAlchemy Object Lifecycle - Part 1
SQLAlchemy Object Lifecycle - Part 1 Recap
Takeaways
- Within a session, we create transactions every time we want to commit work to the database.
- Proposed changes are not immediately committed to the database and instead go through stages to allow for undos.
-
The ability to
undo
is allowed via
db.session.rollback()
Stages:
- Transient : an object exists, it was defined.
user1 = User(name='Amy')
…but not attached to a session (yet).
-
Pending : an object was attached to a session. "Undo" becomes available via
db.session.rollback()
. Waits for a flush to happen -
Flushed : about ready to be committed to the database, translating actions into SQL command statements for the engine.
-
Committed : manually called for a change to persist to the database (permanently); session's transaction is cleared for a new set of changes.
Stage Quiz
QUIZ QUESTION: :
Match the statement to the stage that an object would be in its lifecycle, if the statement was called
ANSWER CHOICES:
Statement |
Stage |
---|---|
flushed |
|
committed |
|
transient |
|
pending |
|
pending |
|
committed |
|
transient |
|
transient |
|
pending |
|
pending |
SOLUTION:
Statement |
Stage |
---|---|
committed |
|
transient |
|
transient |
|
pending |
|
pending |
|
pending |
|
pending |
|
pending |
|
pending |
|
committed |
|
transient |
|
transient |
|
transient |
|
transient |
|
pending |
|
pending |
|
pending |
|
pending |
|
pending |
|
pending |
Stage Q
QUIZ QUESTION: :
Order the stages in correct order
ANSWER CHOICES:
Stage Order |
Stage |
---|---|
Pending |
|
Transient |
|
Committed |
|
Flushed |
SOLUTION:
Stage Order |
Stage |
---|---|
Pending |
|
Transient |
|
Committed |
|
Flushed |
SOLUTION:
- Pending
Stage Quiz 2
SOLUTION:
TransientStage Quiz 3
SOLUTION:
CommittedStage Quiz 4
SOLUTION:
- Pending
- Flushed
Stage Quiz 5